//demo17.cpp 多进程生产消费者模型——消费者

#include "public13.h"

int main()
{
    struct People
    {
        int age;
        char name[51];
    };

    using ElemType = People;

    //初始化共享内存
    int shmid = shmget(0X5005, sizeof(squeue<ElemType, 5>), 0640|IPC_CREAT);
    if(shmid == -1)
    {
        cout << "shmget(0x5005) failed. " << endl;
        return -1;
    }

    //把共享内存连接到当前进程的地址空间
    squeue<ElemType, 5> *QQ = (squeue<ElemType, 5> *)shmat(shmid, 0, 0);        //队列容量为5
    if(QQ == (void *)-1)
    {
        cout << "shmat() failed. " << endl;
    }

    QQ->init();

    ElemType ee;

    csemp mutex; mutex.init(0x5001);            //互斥锁
    csemp cond; cond.init(0x5002, 0, 0);        //条件变量

    while(true)
    {
        mutex.wait();   //加锁

        while(QQ->empty())      //如果队列为空，进入循环，否则直接处理数据，必须用循环队列,不能用if
        {
            mutex.post();       //解锁
            cond.wait();        //等待生产者的唤醒信号
            mutex.wait();       //加锁
        }

        //数据元素出队
        ee = QQ->front(); QQ->pop();
        mutex.post();   //解锁

        //处理出队的数据(消费数据)
        cout << "age = " << ee.age << ",  name = " << ee.name << endl;
        usleep(100);    //模拟处理数据所需时间

    }
    shmdt(QQ);
}
